package com.houyi.sax;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by cdyizuoming on 2017/11/1.
 * 正则工具类，类初始化 进行正则编译，减少runtime Pattern.compile 重复编译消耗
 */
public class PatternUtils {

    private static Map<String, Pattern> patternMap = null;

    static {
        //数字校验
        Pattern digitPattern = Pattern.compile("^(\\d+)(\\.\\d+)?$");
        //正整数校验
        Pattern positivePattern = Pattern.compile("^[1-9]\\d*|0$");
        //正数校验
        Pattern intPattern=Pattern.compile("^[1-9]\\d*$");
        //邮箱校验
        Pattern emailPattern = Pattern.compile("^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w+)+)$");
        //%校验
        Pattern percentPattern = Pattern.compile("^(\\d+)(\\.\\d+)?[%]?$");
        //上线时间校验
        Pattern onlineTimePattern = Pattern.compile("^\\d+(\\.[05])?$");
        patternMap = new HashMap<>();
        patternMap.put("digitPattern", digitPattern);
        patternMap.put("positivePattern", positivePattern);
        patternMap.put("intPattern", intPattern);
        patternMap.put("emailPattern", emailPattern);
        patternMap.put("percentPattern", percentPattern);
        patternMap.put("onlineTimePattern", onlineTimePattern);
    }


    public static boolean patternCheck(String val, String key) {
        Pattern pattern = patternMap.get(key);
        if (null == pattern) {
            return false;
        }
        return pattern.matcher(val).find();
    }

}
